package com.letv.core.sysletvplayer.base.impl;

import android.content.Context;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.letv.android.sdk.R;
import com.letv.core.sysletvplayer.base.BasePlayerPannel;
import com.letv.core.sysletvplayer.utils.Tools;
import com.letv.core.sysletvplayer.view.LetvSeekBar;

import java.util.Calendar;

public class LocalPlayerPannel extends BasePlayerPannel {
	/**上下文**/
	private Context mContext;
	/** 根布局*/
	private RelativeLayout mRootLayout;
	/** 顶部布局 */
	private RelativeLayout mTopRelativeLayout;
	/** 返回按钮 */
	private ImageView mTopBackBtn;
	/** DLNA */
	private Button mDLNABtn;
	/** 小窗*/
	private Button mSmallBtn;
	/** 主标题 */
	private TextView mTopTitleTextView;
	/** 电量情况提示 */
	private ImageView mTopBatteryImageView;
	/** 当前时间提示 */
	private TextView mTopTimeTextView;
	/** 底部根布局 */
	private RelativeLayout mBottomRelativeLayout;
	/** 播放按键 */
	private ImageView mBottomPlayPauseBtn;
	/** 播放控制条*/
	private LetvSeekBar mBottomPlaySeekBar;
	/** 音量布局*/
	private LinearLayout mBottomSoundLinearLayout;
	/** 声音调节按钮*/
	private ImageView mBottomSoundIconBtn;
	/** 声音控制条*/
	private SeekBar mBottomSoundSeekBar;
	/** 加载进度*/
	private ImageView mLoadingIv;
	/** 上下菜单显示*/
	private boolean isShow;
	/** 存储播放状态*/
	private boolean isPlayingBefore;
	/** 加载动画 */
	private Animation mAnimation;
	
	/**控制进度条事件*/
	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			hidePannel();
			return false;
		}
	});

	public LocalPlayerPannel(Context context) {
		super(context);
		this.mContext = context;
		findView();
	}
	
	public void findView() {
		/*根布局*/
		mRootLayout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.letv_local_player_panel_main, null);
		mLoadingIv = (ImageView) mRootLayout.findViewById(R.id.loading_iv);

		/*顶部 */
		mTopRelativeLayout = (RelativeLayout) mRootLayout
				.findViewById(R.id.full_top);
		mTopBackBtn = (ImageView) mRootLayout.findViewById(R.id.full_back);
		mTopTitleTextView = (TextView) mRootLayout.findViewById(R.id.full_title);
		mDLNABtn = (Button) mRootLayout.findViewById(R.id.full_dlna);
		mSmallBtn = (Button) mRootLayout.findViewById(R.id.full_small);
		mTopTimeTextView = (TextView) mRootLayout.findViewById(R.id.full_time);
		mTopBatteryImageView = (ImageView) mRootLayout.findViewById(R.id.full_battery);
		

		/*底部 */
		mBottomRelativeLayout = (RelativeLayout) mRootLayout
				.findViewById(R.id.full_bottom);
		mBottomPlayPauseBtn = (ImageView) mRootLayout.findViewById(R.id.full_play);
		mBottomSoundLinearLayout = (LinearLayout) mRootLayout.findViewById(R.id.full_sound_layout);
		mBottomSoundIconBtn = (ImageView) mRootLayout.findViewById(R.id.full_sound);
		mBottomSoundSeekBar = (SeekBar) mRootLayout.findViewById(R.id.full_sound_seekbar);
		mBottomPlaySeekBar = (LetvSeekBar) mRootLayout.findViewById(R.id.full_play_seekbar);
		
		/*监听事件*/
		mTopBackBtn.setOnClickListener(backClick);
		mDLNABtn.setOnClickListener(dlnaClick);
		mSmallBtn.setOnClickListener(smallClick);
		mBottomPlayPauseBtn.setOnClickListener(playClick);
		mBottomSoundIconBtn.setOnClickListener(vloumeIconClick);
		mBottomSoundSeekBar.setOnSeekBarChangeListener(volumeSeekBarChangeListener);
		mBottomPlaySeekBar.setOnSeekBarChangeListener(playSeekBarChangeListener);
		
		updateTimer();
		isShow = true;
		startHandlerHide();
	}
	
	public void play() {
		mBottomPlayPauseBtn.setImageResource(R.drawable.letv_local_play_controller_pause_btn_selector);
		mBottomPlayPauseBtn.setOnClickListener(pauseClick);
	}

	public void pause() {
		mBottomPlayPauseBtn.setImageResource(R.drawable.letv_local_play_controller_play_btn_selector);
		mBottomPlayPauseBtn.setOnClickListener(playClick);
	}

	public View getContentView() {
		return mRootLayout;
	}
	
	public void initTitle(final String title, boolean islandscape) {
		if (!TextUtils.isEmpty(title)) {
			
//			int maxwidth;
//			if(islandscape) {
//				maxwidth = 486;
//			} else {
//				maxwidth = 238;
//			}
//			
//			TextPaint paint = mTopTitleTextView.getPaint();
//			float textLength = paint.measureText(title);
//			if(textLength > maxwidth) {
//				
//				StringBuilder temp = new StringBuilder();
//				temp.append("...");
//				int start = title.lastIndexOf(".");
//				int end = title.length();
//				if (start != -1) {
//					temp.append(title.substring(start, end));
//				} else {
//					start = title.lastIndexOf("(");
//					temp.append(title.substring(start, end));
//				}
//				
//				float textSuffixLength = paint.measureText(temp.toString());
//				int length = (int) (maxwidth - textSuffixLength);
//				
//				float charWidth = 0;
//				int index = 0;
//				char[] textCharArray = title.toCharArray();
//				for (int i = 0; i < textCharArray.length; i++) {
//					charWidth = paint.measureText(textCharArray, 0, i);
//					if(charWidth > length) {
//						index = i - 1;
//						break;
//					}
//				} 
//				String substr = title.substring(0, index);
//				mTopTitleTextView.setText(substr + temp.toString());
//			} else {
				mTopTitleTextView.setText(title);
				mTopTitleTextView.setSelected(true);
//			}
		}
	}
	
	@Override
	public void initVolume(int cur, int max) {
		mBottomSoundSeekBar.setProgress(cur);
		mBottomSoundSeekBar.setMax(max);
		mBottomSoundSeekBar.setOnSeekBarChangeListener(volumeSeekBarChangeListener);
		changeSoundState(cur , max);
//		Log.i("chenyg", "initVolume()---->Progress=" + cur + ", max=" + max);
	}

	@Override
	public void updateVolume(int cur, int max) {
//		mBottomSoundSeekBar.setMax(max);
		mBottomSoundSeekBar.setProgress(cur);
		changeSoundState(cur , max);
//		Log.i("chenyg", "updateVolume()---->Progress=" + cur + ", max=" + max);
	}
	
	@Override
	public void initProgress(int curTime, int totleTime) {
		mBottomPlaySeekBar.setMax(totleTime);
		mBottomPlaySeekBar.setEndTime(totleTime * 1000);
		mBottomPlaySeekBar.setProgress(curTime);
		mBottomPlaySeekBar.setOnSeekBarChangeListener(playSeekBarChangeListener);
		mBottomPlaySeekBar.setEnabled(true);
//		Log.i("chenyg", "initProgress()---->curTime=" + curTime + ", totleTime=" + totleTime);
	}
	
	@Override
	public void updateProgress(int curPos, int total) {
		mBottomPlaySeekBar.setProgress(curPos);
//		mBottomPlaySeekBar.setMax((int)total);
//		mBottomPlaySeekBar.invalidate();
//		Log.i("chenyg", "updateProgress()---->curPos=" + curPos + ", total=" + total);
	}
	
	@Override
	public void showLoading() {
		LinearInterpolator li = new LinearInterpolator();
		mAnimation = AnimationUtils.loadAnimation(mContext, R.anim.letv_local_play_anim_loading);
		mAnimation.setInterpolator(li);
		mLoadingIv.setVisibility(View.VISIBLE);
		mLoadingIv.startAnimation(mAnimation);
	}
	
	@Override
	public void finishLoading() {
		mLoadingIv.clearAnimation();
		mLoadingIv.setVisibility(View.GONE);
	}

	/**
	 * 点击返回的监听
	 * */
	private OnClickListener backClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			startHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onBack();
			}
		}
	};
	
	/**
	 * 点击dlna的监听
	 * */
	private OnClickListener dlnaClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			//...DLNA监听
			if(mPlayerController != null) {
				mPlayerController.onDlna();
			}
		}
	};
	
	/**
	 * 点击小窗的监听
	 * */
	private OnClickListener smallClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			//...小窗监听
			if(mPlayerController != null) {
				mPlayerController.onSmall();
			}
		}
	};
	
	/**
	 * 点击暂停的监听
	 * */
	private OnClickListener pauseClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			stopHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onPause();
			}
			pause();
		}
	};
	
	/**
	 * 点击播放的监听
	 * */
	private OnClickListener playClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			startHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onStart();
			}
			play();
		}
	};

	/**
	 * 点击快进的监听
	 * */
	private OnClickListener forwardClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			startHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onForward();
			}
		}
	};

	/**
	 * 点击快退的监听
	 * */
	private OnClickListener rewindClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			startHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onRewind();
			}
		}
	};
	
	/**
	 * 进度条变化的监听
	 * */
	private LetvSeekBar.OnSeekBarChangeListener playSeekBarChangeListener = new LetvSeekBar.OnSeekBarChangeListener() {

		private int preProgress = -1;
		private boolean istouched = false;
		
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			startHandlerHide();
			if (mPlayerController != null) {
				mPlayerController.onStopTrackingTouch();
				mPlayerController.onSeekTo(seekBar.getProgress());
			}
			
			if(isPlayingBefore){
				play();
			} else {
				pause();
			}
			
			istouched = false;
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			stopHandlerHide();
			if(mPlayerController != null) {
				mPlayerController.onStartTrackingTouch();
				isPlayingBefore = mPlayerController.isPlaying();
			}
			
			istouched = true;
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			Log.i("chenyg", "---->fromUser=" + fromUser + ", preProgress=" + preProgress + ", progress=" + progress);
			
			if (istouched) {
				if (preProgress > progress) {
					mBottomPlayPauseBtn.setImageResource(R.drawable.letv_local_rewind);
				} else {
					mBottomPlayPauseBtn.setImageResource(R.drawable.letv_local_forword);
				}
				preProgress = progress;
			}
			
//			if(mPlayerController != null) {
//				mPlayerController.onSeekTo(progress); //实时更新进度
//			}
			
		}
	};
	
	/**
	 * 点击声音的监听
	 * */
	private OnClickListener vloumeIconClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (mBottomSoundLinearLayout.getVisibility() != View.VISIBLE) {

				int[] locations = new int[2];
				mBottomSoundIconBtn.getLocationOnScreen(locations);
				int x = locations[0];// 获取组件当前位置的横坐标
				int y = locations[1];// 获取组件当前位置的纵坐标
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mBottomSoundLinearLayout.getLayoutParams();
				params.leftMargin = x + (mBottomSoundIconBtn.getMeasuredWidth() - mBottomSoundLinearLayout.getMeasuredWidth())/2;
				params.topMargin = y - mBottomSoundLinearLayout.getMeasuredHeight();

				mBottomSoundLinearLayout.setLayoutParams(params);
				mBottomSoundLinearLayout.requestLayout();
				mBottomSoundLinearLayout.setVisibility(View.VISIBLE);
			} else {
				mBottomSoundLinearLayout.setVisibility(View.INVISIBLE);
			}
		}
	};
	
	/**
	 * 声音进度条变化的监听
	 * */
	private OnSeekBarChangeListener volumeSeekBarChangeListener = new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			startHandlerHide();
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			stopHandlerHide() ;
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//			startHandlerHide();
			int max = seekBar.getMax();
//			Log.i("chenyg", "onProgressChanged()--->progress=" + progress + ", max=" + max );
//			int volumeMax = setSoundVolume(progress);
			mPlayerController.onSoundChange(progress, max);
			changeSoundState(progress, max);
//			if (max != volumeMax) {
//				if (progress <= max) {
//					seekBar.setMax(volumeMax);
//				} else {
//					seekBar.setProgress(max);
//				}
//			}
		}
	};
	
	/**
	 * 改变声音状态显示
	 */
	public void changeSoundState(int curValue, int maxValue) {
		if (mBottomSoundIconBtn != null) {
			if (curValue >= maxValue / 3 * 2) {
				mBottomSoundIconBtn.setImageResource(R.drawable.letv_local_play_controller_sound_three_selector);
			} else if (curValue >= maxValue / 3) {
				mBottomSoundIconBtn.setImageResource(R.drawable.letv_local_play_controller_sound_two_selector);
			} else if (curValue > 0) {
				mBottomSoundIconBtn.setImageResource(R.drawable.letv_local_play_controller_sound_one_selector);
			} else {
				mBottomSoundIconBtn.setImageResource(R.drawable.letv_local_play_controller_sound_zero_selector);
			}
		}
	}
	
	/**
	 * 隐藏控制面板
	 */
	private void startHandlerHide() {
		if (isShow) {
			handler.removeMessages(1);
			handler.sendEmptyMessageDelayed(1, 5000);
		}
	}

	/**
	 * 移除自动隐藏
	 */
	private void stopHandlerHide() {
		handler.removeMessages(1);
	}

	@Override
	public void showOrHidePannel() {
		if(isShow) {
			hidePannel();
			stopHandlerHide();
		} else {
			showPannel();
			startHandlerHide();
		}
	}
	
	private void showPannel() {
		mTopRelativeLayout.setVisibility(View.VISIBLE);
		mBottomRelativeLayout.setVisibility(View.VISIBLE);
		isShow = true;
	}
	
	private void hidePannel() {
		mTopRelativeLayout.setVisibility(View.INVISIBLE);
		mBottomRelativeLayout.setVisibility(View.INVISIBLE);
		mBottomSoundLinearLayout.setVisibility(View.INVISIBLE);
		isShow = false;
	}
	
	/**
	 * 更新时间显示
	 */
	private void updateTimer() {
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(System.currentTimeMillis());
		int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
		int minite = mCalendar.get(Calendar.MINUTE);
		mTopTimeTextView.setText(Tools.getStringTwo(String.valueOf(hour)) + ":" + Tools.getStringTwo(String.valueOf(minite)));
	}
	
	//----------------------------------------------------------------------
	
	/**
	 * 时间的改变
	 */
	@Override
	public void onTimeChange() {
		if (mTopTimeTextView.getVisibility() != View.VISIBLE) {
//			mTopTimeTextView.setVisibility(View.VISIBLE);
		}
		updateTimer();
	}
	
	/**
	 * 电量的改变
	 */
	@Override
	public void onBatteryChange(int curStatus, int curPower) {
		if (mTopBatteryImageView.getVisibility() != View.VISIBLE) {
//			mTopBatteryImageView.setVisibility(View.VISIBLE);
		}
		boolean isCharging = false;

		switch (curStatus) {
		case BatteryManager.BATTERY_STATUS_CHARGING:// 充电状态
			isCharging = true;
			break;
		case BatteryManager.BATTERY_STATUS_DISCHARGING:// 放电状态
			break;
		case BatteryManager.BATTERY_STATUS_NOT_CHARGING:// 未充电
			break;
		case BatteryManager.BATTERY_STATUS_FULL:// 充满电
			break;
		case BatteryManager.BATTERY_STATUS_UNKNOWN:// 未知状态
			break;
		default:
			break;
		}

		if (isCharging) {
			mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery_charge);
		} else {
			if (curPower >= 80) {
				mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery5);
			} else if (curPower >= 60) {
				mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery4);
			} else if (curPower >= 40) {
				mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery3);
			} else if (curPower >= 20) {
				mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery2);
			} else if (curPower >= 0) {
				mTopBatteryImageView.setImageResource(R.drawable.letv_local_battery1);
			}
		}
	}

	@Override
	public void onNetChange() {
		
	}

	@Override
	public void onScreenOn() {
		
	}

	@Override
	public void onScreenOff() {
		
	}

	@Override
	public void onUserPersent() {
		
	}

}

